<template>
  <ContentDetailWrap :title="t('warehouse.add')">
    <template #header>
      <BaseButton @click="go(-1)">
        {{ t('common.back') }}
      </BaseButton>
      <BaseButton type="primary" :loading="loading" @click="submit(formRef)">
        {{ t('action.save') }}
      </BaseButton>
    </template>
    <!--    表单-->
    <el-form
      :model="form"
      inline
      ref="formRef"
      :rules="rules as FormRules"
      :hide-required-asterisk="true"
      label-width="110px"
    >
      <el-form-item :label="t('dealerAssetManagement.customer')">
        <el-button class="m-l-20px" size="small" type="primary" @click="handleOpenCustomer"
          >{{ t('dealerAssetManagement.select') }}
        </el-button>
      </el-form-item>
      <el-form-item class="m-l-200px" :label="t('dealerAssetManagement.customerName')">
        <el-input
          v-model="form.customer.username"
          clearable
          disabled
          placeholder=" "
          style="width: 250px"
        />
      </el-form-item>
      <el-form-item :label="t('dealerAssetManagement.customerEmailAddress')">
        <el-input
          v-model="form.customer.email"
          clearable
          disabled
          placeholder=" "
          style="width: 250px"
        />
      </el-form-item>
      <el-form-item class="" :label="t('order.owner')" required>
        <el-input v-model="ownerName" clearable disabled :placeholder="t('order.owner')">
          <template #append>
            <el-button size="small" text type="success" @click="handleOpenOwner">{{
              t('dealerAssetManagement.select')
            }}</el-button>
          </template>
        </el-input>
      </el-form-item>
      <el-form-item :label="t('order.partner')">
        <el-input v-model="partnerName" clearable disabled :placeholder="t('order.partner')">
          <template #append>
            <el-button size="small" text type="success" @click="handleOpenPartner">{{
              t('dealerAssetManagement.select')
            }}</el-button>
          </template>
        </el-input>
      </el-form-item>
      <!--      分割线-->
      <div class="h-1px w-full bg-[#c8c9cc] my-10px"></div>
      <!--      商品-->
      <el-form-item class="m-t-20px" :label="t('dealerAssetManagement.commodity')">
        <el-button class="m-l-20px" type="primary" size="small" @click="handleOpenShop"
          >{{ t('dealerAssetManagement.select') }}
        </el-button>
      </el-form-item>
      <!-- 选择商品列表 -->
      <el-table
        :data="form.tableList"
        highlight-current-row
        stripe
        border
        :cell-style="{ textAlign: 'center' }"
        :header-cell-style="{ textAlign: 'center' }"
      >
        <!-- <el-table-column
          :label="t('dealerAssetManagement.warehouse')"
          min-width="200"
          :show-overflow-tooltip="true"
        >
          <template #default="{ row }">
            {{ useEnumeratePicker(warehouseList, row.wid) }}
          </template>
        </el-table-column> -->
        <el-table-column
          :label="t('wholesalOrder.warehouse')"
          :width="calculateColumnWidth(form.tableList, 'wid', 2)"
          :show-overflow-tooltip="true"
        >
          <template #default="{ row }">
            {{ useEnumeratePicker(warehouseList, row.wid) }}
          </template>
        </el-table-column>
        <el-table-column
          :label="t('dealerAssetManagement.nameCall')"
          prop="product_name"
          :width="calculateColumnWidth(form.tableList, 'product_name')"
          :show-overflow-tooltip="true"
        />
        <el-table-column
          :label="t('dealerAssetManagement.type')"
          :width="calculateColumnWidth(form.tableList, 'type')"
          :show-overflow-tooltip="true"
        >
          <template #default="{ row }">
            {{ useEnumeratePicker(typeList, row.is_futures) }}
          </template>
        </el-table-column>
        <el-table-column
          :label="t('dealerAssetManagement.pendingQuantity')"
          prop="quantity"
          min-width="120"
          :show-overflow-tooltip="true"
        />
        <el-table-column
          :label="t('dealerAssetManagement.theNumberOfShipments')"
          min-width="140"
          :show-overflow-tooltip="true"
        >
          <template #default="{ row }">
            <el-input-number
              v-model="row!.ship_quantity"
              :min="1"
              :max="row!.quantity ? parseInt(row!.quantity as string) : 100000"
              @change="handleCalcFreightPrice"
            />
          </template>
        </el-table-column>
        <el-table-column
          :label="t('dealerAssetManagement.coding')"
          prop="code"
          min-width="120"
          :show-overflow-tooltip="true"
        />
        <el-table-column
          :label="t('dealerAssetManagement.brand')"
          min-width="120"
          :show-overflow-tooltip="true"
        >
          <template #default="{ row }">
            {{ useEnumeratePicker(brandList, row.brand) }}
          </template>
        </el-table-column>
        <el-table-column
          :label="t('dealerAssetManagement.computingPower')"
          prop="hashrate"
          :width="calculateColumnWidth(form.tableList, 'hashrate')"
          :show-overflow-tooltip="true"
        />
        <el-table-column
          :label="t('dealerAssetManagement.warranty')"
          prop="expiration_date"
          :width="calculateColumnWidth(form.tableList, 'expiration_date')"
          :show-overflow-tooltip="true"
        />
        <!-- <el-table-column
          :label="t('dealerAssetManagement.arrivalDate')"
          prop="arrival_date"
          :width="calculateColumnWidth(form.tableList, 'code')"
          :show-overflow-tooltip="true"
        /> -->
        <el-table-column fixed="right" :label="t('common.operation')" width="200">
          <template #default="{ $index }">
            <el-button type="danger" @click="handleDelete($index)" size="small">
              {{ t('wholesalOrder.delete') }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <!--      分割线-->
      <div class="h-1px w-full bg-[#c8c9cc] m-t-40px m-b-20px"></div>
      <!--      账单地址-->
      <el-form-item :label="t('order.billing_address')" class="block">
        <el-input
          v-model="form.billingAddress.address"
          disabled
          placeholder=" "
          style="width: 100%"
        >
          <template #append>
            <el-button size="small" text type="success" @click="handleSelectBillingAddress">
              {{ t('dealerAssetManagement.select') }}
            </el-button>
          </template>
        </el-input> </el-form-item
      ><br />
      <!--      收货方式-->
      <el-form-item :label="t('dealerAssetManagement.receiptMethod')">
        <el-radio-group
          class="m-l-20px"
          v-model="form.receiptMethod"
          @change="handleReceiptMethodChange"
        >
          <el-radio v-for="item in receiptMethodList" :key="item.value" :label="item.value"
            >{{ item.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <!--      分割线-->
      <div class="h-1px w-full bg-[#c8c9cc] m-b-20px" v-if="form.receiptMethod === 0"></div>
      <!--      自提地址-->
      <el-form-item
        :label="t('dealerAssetManagement.pickUpAddress')"
        v-if="form.receiptMethod === 0"
      >
        <el-input
          class="m-l-20px"
          v-model="form.selfPickupInfo.pickUpAddress"
          disabled
          placeholder=" "
          style="width: 1000px"
        />
      </el-form-item>
      <div v-if="form.receiptMethod === 0">
        <el-form-item
          :label="t('dealerAssetManagement.selfPickupInformation')"
          prop="selfPickupInfo.name"
        >
          <el-input
            class="m-l-20px"
            v-model="form.selfPickupInfo.name"
            :placeholder="t('dealerAssetManagement.nameMsg')"
            style="width: 250px"
          />
        </el-form-item>
        <el-form-item label=" " prop="selfPickupInfo.phone">
          <el-input
            v-model="form.selfPickupInfo.phone"
            :placeholder="t('dealerAssetManagement.phoneMsg')"
            style="width: 250px"
          />
        </el-form-item>
        <el-form-item label=" " prop="selfPickupInfo.passport">
          <el-input
            v-model="form.selfPickupInfo.passport"
            :placeholder="t('dealerAssetManagement.passportMsg')"
            style="width: 250px"
          />
        </el-form-item>
        <el-form-item label=" ">
          <el-input
            v-model="form.selfPickupInfo.vehicleInfo"
            :placeholder="t('dealerAssetManagement.vehicleInfoMsg')"
            style="width: 800px"
          />
        </el-form-item>
      </div>

      <!--      分割线-->
      <div class="h-1px w-full bg-[#c8c9cc] m-b-20px" v-if="form.receiptMethod === 2"></div>
      <!--      自提地址-->
      <div v-if="form.receiptMethod === 2">
        <el-form-item :label="t('dealerAssetManagement.information')" prop="selfPickupInfo.name">
          <el-input
            class="m-l-20px"
            v-model="form.selfPickupInfo.name"
            :placeholder="t('dealerAssetManagement.nameMsg')"
            style="width: 250px"
          />
        </el-form-item>
        <el-form-item label=" " prop="selfPickupInfo.phone">
          <el-input
            v-model="form.selfPickupInfo.phone"
            :placeholder="t('dealerAssetManagement.phoneMsg')"
            style="width: 250px"
          />
        </el-form-item>
        <el-form-item label=" " prop="selfPickupInfo.passport">
          <el-input
            v-model="form.selfPickupInfo.passport"
            :placeholder="t('dealerAssetManagement.passportMsg')"
            style="width: 250px"
          />
        </el-form-item>
        <el-form-item label=" ">
          <el-input
            v-model="form.selfPickupInfo.warehouseCode"
            :placeholder="t('dealerAssetManagement.warehouseCodeMsg')"
            style="width: 800px"
          />
        </el-form-item>
      </div>

      <!--      分割线-->
      <div class="h-1px w-full bg-[#c8c9cc] m-b-20px" v-if="form.receiptMethod === 1"></div>
      <!--        收货地址-->
      <el-form-item
        :label="t('dealerAssetManagement.deliveryAddress')"
        v-if="form.receiptMethod === 1"
      >
        <el-button class="m-l-20px" type="primary" size="small" @click="handleSelectAddress">
          {{ t('dealerAssetManagement.select') }}
        </el-button>
      </el-form-item>
      <el-form-item
        :label="t('order.freight')"
        v-if="form.receiptMethod === 1"
        prop="deliveryAddress.freight"
      >
        <el-input
          v-model="form.deliveryAddress.freight"
          placeholder=" "
          :disabled="freightCollect"
          @input="
            (e: string) =>
              (form.deliveryAddress.freight = e
                .replace(/[^\d.]/g, '')
                .replace(/\.{2,}/g, '.')
                .replace('.', '$#$')
                .replace(/\./g, '')
                .replace('$#$', '.')
                .replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3')
                .replace(/^\./g, ''))
          "
          style="width: 250px"
        />
      </el-form-item>
      <!-- 新增：是否到付选项 -->
      <el-form-item label=" " v-if="form.receiptMethod === 1">
        <el-checkbox v-model="freightCollect" @change="handleFreightCollectChange">{{
          t('dealerAssetManagement.freightCollect')
        }}</el-checkbox>
      </el-form-item>
      <el-form-item
        :label="t('dealerAssetManagement.deliveryAddress')"
        v-if="form.receiptMethod === 1"
      >
        <el-input
          v-model="form.deliveryAddress.address"
          disabled
          placeholder=" "
          style="width: 800px"
        />
      </el-form-item>
      <div class="flex flex-col" v-if="form.receiptMethod === 1">
        <el-form-item :label="t('dealerAssetManagement.aging')">
          <el-radio-group class="m-l-20px" v-model="form.aging" @change="handleChangeAging">
            <el-radio v-for="item in agingList" :key="item.value" :label="item.value"
              >{{ item.label }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item :label="t('dealerAssetManagement.howToFileYourTaxes')">
          <el-radio-group
            class="m-l-20px"
            v-model="form.howToFileYourTaxes"
            @change="handleChangeTax"
          >
            <el-radio v-for="item in howToFileYourTaxesList" :key="item.value" :label="item.value">
              {{ item.label }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
      </div>
      <!--      分割线-->
      <div class="h-1px w-full bg-[#c8c9cc] m-b-20px"></div>
      <!--      备注-->
      <div>
        <el-form-item :label="t('order.order_remark')">
          <el-input
            class="m-l-20px"
            v-model="form.order_remark"
            type="textarea"
            style="width: 350px"
            :autosize="{ minRows: 5, maxRows: 10 }"
            maxlength="600"
            :placeholder="t('order.order_remark')"
          />
        </el-form-item>
      </div>
      <!--      备注-->
      <el-form-item :label="t('order.notes')">
        <el-input
          class="m-l-20px"
          v-model="form.notes"
          type="textarea"
          style="width: 350px"
          :autosize="{ minRows: 5, maxRows: 10 }"
          maxlength="600"
          :placeholder="t('order.notes')"
        />
      </el-form-item>
    </el-form>
  </ContentDetailWrap>
  <!--  选择客户弹框-->
  <DialogCustomerChecked
    ref="DialogCustomerCheckedRef"
    @expose-multiple-data="getExposeCustomerData"
    :multiple="false"
  />
  <!--  选择商品弹框-->
  <DialogShopChecked ref="DialogShopCheckedRef" @expose-multiple-data="getExposeMultipleData" />
  <!--  选择地址弹框-->
  <DialogSelectAddress ref="DialogSelectAddressRef" @expose-multiple-data="getExposeAddressData" />
  <!--  选择账单地址弹框-->
  <DialogSelectBillingAddress
    ref="DialogSelectBillingAddressRef"
    @expose-multiple-data="getExposeBillingAddressData"
  />
  <!--  选择负责人弹框-->
  <DialogOperatorChecked
    ref="DialogOwnerCheckedRef"
    @expose-multiple-data="getExposeOwnerData"
    class="mobile-dialog"
  />
  <!--  选择合伙人弹框-->
  <DialogOperatorChecked
    ref="DialogPartnerCheckedRef"
    :multiple="true"
    @expose-multiple-data="getExposePartnerData"
  />
</template>
<script setup lang="ts">
import DialogOperatorChecked from '../../Authorization/Operator/components/DialogChecked/index.vue'
import DialogCustomerChecked from '../../Customer/Customer/components/DialogChecked/index.vue'
import DialogShopChecked from './components/DialogShopChecked/index.vue'
import DialogSelectAddress from './components/DialogSelectAddress/index.vue'
import DialogSelectBillingAddress from './components/DialogSelectBillingAddress/index.vue'
import { ContentDetailWrap } from '@/components/ContentDetailWrap'
import { useEnumeratePicker, calculateColumnWidth } from '@/utils'
import { ElMessage, ElMessageBox, type FormRules, type FormInstance, ElLoading } from 'element-plus'
import {
  createDataApi,
  getEnumApi,
  getPickUpAddressApi,
  getFreightApi
} from '@/api/order/dealerAssetManagement'
import { getListApi } from '@/api/order/dealerAssetManagement'

import { getOrderEnumApi } from '@/api/order'
import { useDebounceFn } from '@vueuse/core'
import { getCustomerListApi } from '@/api/wholesalOrder'
import { useUserStore } from '@/store/modules/user'
const userStore = useUserStore()

const { t } = useI18n()
const route = useRoute()
const { push, go } = useRouter()

const loading = ref<boolean>(false)
const formRef = ref<FormInstance>()
// 新增：是否到付响应式变量
const freightCollect = ref<boolean>(false)
const form = ref<Record<string, any>>({
  customer: {
    user_id: '',
    username: '',
    email: '',
    role: ''
  },
  owner: '',
  tableList: [],
  receiptMethod: 1,
  selfPickupInfo: {
    pickUpAddress: '',
    name: '',
    phone: '',
    passport: '',
    warehouseCode: '',
    vehicleInfo: ''
  },
  deliveryAddress: {
    id: '',
    address: '',
    freight: ''
  },
  billingAddress: {
    id: '',
    address: ''
  },
  aging: 1,
  howToFileYourTaxes: 1,
  notes: '',
  order_remark: ''
})
// 新增：处理是否到付复选框变化的函数
const handleFreightCollectChange = (checked: boolean) => {
  if (checked) {
    // 如果选中“到付”，设置运费为0，并禁用输入框
    form.value.deliveryAddress.freight = '0'
  } else {
    // 如果取消“到付”，启用输入框，不清空当前值（如果需要清空，可以设置为 ''）
    // form.value.deliveryAddress.freight = ''; // 根据需求决定是否清空
  }
  // 可选：触发一次运费计算（如果取消到付且地址已选）
  if (!checked && form.value.deliveryAddress.id) {
    getShippingRates()
  }
}
const addressRow = ref<Record<string, any>>({})

const rules = ref<FormRules>({
  'selfPickupInfo.name': [
    {
      required: true,
      message: t('dealerAssetManagement.nameMsg'),
      trigger: 'blur'
    }
  ],
  'selfPickupInfo.phone': [
    {
      required: true,
      message: t('dealerAssetManagement.phoneMsg'),
      trigger: 'blur'
    }
  ],
  'selfPickupInfo.passport': [
    {
      required: true,
      message: t('dealerAssetManagement.passportMsg'),
      trigger: 'blur'
    }
  ],
  'deliveryAddress.freight': [
    {
      required: true,
      message: '请填写运费',
      trigger: 'blur'
    }
  ]
})

const DialogCustomerCheckedRef = ref<InstanceType<typeof DialogCustomerChecked>>()
const DialogPartnerCheckedRef = ref<InstanceType<typeof DialogOperatorChecked>>() // 合伙人
const DialogShopCheckedRef = ref<InstanceType<typeof DialogShopChecked>>()
const DialogSelectAddressRef = ref<InstanceType<typeof DialogSelectAddress>>()
const DialogSelectBillingAddressRef = ref<InstanceType<typeof DialogSelectBillingAddress>>()

const brandList = ref<Array<Record<string, any>>>([])
const warehouseList = ref<Array<Record<string, any>>>([])
const typeList = ref<Array<Record<string, any>>>([])
const receiptMethodList = ref<Array<Record<string, any>>>([])
const agingList = ref<Array<Record<string, any>>>([])
const howToFileYourTaxesList = ref<Array<Record<string, any>>>([])

//打开选择客户弹框
const handleOpenCustomer = () => {
  nextTick(() => {
    DialogCustomerCheckedRef!.value!.dialogVisible = true
    DialogCustomerCheckedRef!.value!.initialize(
      form.value.customer.user_id
        ? [
            {
              ...form.value.customer,
              id: form.value.customer.user_id
            }
          ]
        : [],
      'distributor'
    )
  })
}

//打开选择商品弹框
const handleOpenShop = () => {
  if (!form.value.customer.user_id)
    return ElMessage.warning(t('common.selectText') + ' ' + t('dealerAssetManagement.customer'))
  nextTick(() => {
    DialogShopCheckedRef!.value!.dialogVisible = true
    DialogShopCheckedRef!.value!.initialize(form.value.tableList, form.value.customer.user_id)
  })
}

//打开选择地址弹框
const handleSelectAddress = () => {
  if (!form.value.customer.user_id)
    return ElMessage.warning(t('common.selectText') + ' ' + t('dealerAssetManagement.customer'))
  if (!form.value.tableList.length)
    return ElMessage.warning(t('common.selectText') + ' ' + t('dealerAssetManagement.product'))
  nextTick(() => {
    DialogSelectAddressRef!.value!.dialogVisible = true
    DialogSelectAddressRef!.value!.initialize(
      form.value.customer.user_id,
      form.value.deliveryAddress.id
        ? [
            {
              id: form.value.deliveryAddress.id
            }
          ]
        : []
    )
  })
}

//切换时效
const handleChangeAging = () => {
  if (!form.value.customer.user_id) {
    form.value.aging = form.value.aging === 1 ? 2 : 1
    return ElMessage.warning(t('common.selectText') + ' ' + t('dealerAssetManagement.customer'))
  }
  if (!form.value.tableList.length) {
    form.value.aging = form.value.aging === 1 ? 2 : 1
    return ElMessage.warning(t('common.selectText') + ' ' + t('dealerAssetManagement.product'))
  }
  if (!form.value.deliveryAddress.id) {
    form.value.aging = form.value.aging === 1 ? 2 : 1
    return ElMessage.warning(
      t('common.selectText') + ' ' + t('dealerAssetManagement.deliveryAddress')
    )
  }
  getShippingRates()
}

//切换报税方式
const handleChangeTax = () => {
  if (!form.value.customer.user_id) {
    form.value.howToFileYourTaxes = form.value.howToFileYourTaxes === 1 ? 2 : 1
    return ElMessage.warning(t('common.selectText') + ' ' + t('dealerAssetManagement.customer'))
  }
  if (!form.value.tableList.length) {
    form.value.howToFileYourTaxes = form.value.howToFileYourTaxes === 1 ? 2 : 1
    return ElMessage.warning(t('common.selectText') + ' ' + t('dealerAssetManagement.product'))
  }
  if (!form.value.deliveryAddress.id) {
    form.value.howToFileYourTaxes = form.value.howToFileYourTaxes === 1 ? 2 : 1
    return ElMessage.warning(
      t('common.selectText') + ' ' + t('dealerAssetManagement.deliveryAddress')
    )
  }
  getShippingRates()
}

//切换收货方式
const handleReceiptMethodChange = async (e: number) => {
  if (e != 0) {
    form.value.selfPickupInfo.vehicleInfo = ''
  }
  if (e != 2) {
    form.value.selfPickupInfo.warehouseCode = ''
  }
  // 新增：如果切换到的不是快递方式（1），则重置“是否到付”为false
  if (e !== 1) {
    freightCollect.value = false
  }
  if (e === 0) {
    if (!form.value.tableList.length) {
      ElMessage.warning(t('common.selectText') + ' ' + t('dealerAssetManagement.product'))
      form.value.receiptMethod = 1
      return
    }
    const resp = await getPickUpAddressApi(form.value.tableList[0].wid)
    form.value.selfPickupInfo.pickUpAddress = resp.data.address
  }
}

//获取运费
const getShippingRates = async () => {
  // 新增：如果选择的是到付，则不计算运费
  if (freightCollect.value) {
    return
  }
  const params = {
    currency: form.value.currency,
    terms: form.value.howToFileYourTaxes,
    to_nation: addressRow.value.to_nation,
    prescription: form.value.aging,
    product_list: form.value.tableList.flatMap((item: any) => [
      {
        id: item.product_id,
        wid: item.wid,
        num: item.ship_quantity,
        billing_weight: item.billing_weight,
        free_shipping: !!item.free_shipping,
        apply_rules: !!item.apply_rules
      }
    ])
  }
  let loadingInstance = {} as Record<string, any>
  try {
    loading.value = true
    loadingInstance = ElLoading.service({
      text: t('dealerAssetManagement.queryFreight'),
      background: 'rgba(0, 0, 0, 0.7)',
      fullscreen: true,
      lock: true
    })
    const freightResp = await getFreightApi(params)
    form.value.deliveryAddress.freight = freightResp.data.logistics_fee
    await nextTick(() => {
      formRef.value!.clearValidate(['deliveryAddress.freight'])
      loadingInstance.close()
    })
  } catch (e) {
    await nextTick(() => {
      loadingInstance.close()
    })
  } finally {
    loading.value = false
  }
}

const submit = async (formEl: FormInstance | undefined) => {
  try {
    if (!formEl) return
    loading.value = true
    await formEl.validate(async (valid) => {
      if (valid) {
        if (!form.value.customer.user_id)
          return ElMessage.warning(
            t('common.selectText') + ' ' + t('dealerAssetManagement.customer')
          )
        if (!form.value.tableList.length)
          return ElMessage.warning(
            t('common.selectText') + ' ' + t('dealerAssetManagement.product')
          )
        if (!form.value.owner)
          return ElMessage.warning(t('common.selectText') + ' ' + t('dealerAssetManagement.owner'))
        if (form.value.receiptMethod === 1 && !form.value.deliveryAddress.id) {
          return ElMessage.warning(
            t('common.selectText') + ' ' + t('dealerAssetManagement.deliveryAddress')
          )
        }
        const params = {
          wid: form.value.tableList[0].wid || '',
          user_id: form.value.customer.user_id,
          list: form.value.tableList,
          delivery_method: form.value.receiptMethod,
          notes: form.value.notes,
          order_remark: form.value.order_remark,
          owner: form.value.owner,
          partner: form.value.partner,
          // 新增：提交到付字段
          freight_collect: freightCollect.value,
          // 自提
          ...(form.value.receiptMethod === 0 && { name: form.value.selfPickupInfo.name }),
          ...(form.value.receiptMethod === 0 && { phone: form.value.selfPickupInfo.phone }),
          ...(form.value.receiptMethod === 0 && { passport: form.value.selfPickupInfo.passport }),
          ...(form.value.receiptMethod === 0 && {
            vehicle: form.value.selfPickupInfo.vehicleInfo
          }),
          // 仓内过货
          ...(form.value.receiptMethod === 2 && { name: form.value.selfPickupInfo.name }),
          ...(form.value.receiptMethod === 2 && { phone: form.value.selfPickupInfo.phone }),
          ...(form.value.receiptMethod === 2 && { passport: form.value.selfPickupInfo.passport }),
          ...(form.value.receiptMethod === 2 && {
            warehouse_code: form.value.selfPickupInfo.warehouseCode
          }),
          //快递
          ...(form.value.receiptMethod === 1 && { address_id: form.value.deliveryAddress.id }),
          ...(form.value.receiptMethod === 1 && {
            logistics_fee: form.value.deliveryAddress.freight
          }),
          ...(form.value.receiptMethod === 1 && { prescription: form.value.aging }),
          ...(form.value.receiptMethod === 1 && {
            delivery_terms: form.value.howToFileYourTaxes
          }),
          billing_address_id: form.value.billingAddress.id
        } as unknown as Record<string, any>
        const resp = await createDataApi(params)
        if (resp.code === 0) {
          ElMessage.success(t('dealerAssetManagement.createSucMsg'))
          push('/order/dealerAssetManagement')
        }
      }
    })
  } finally {
    loading.value = false
  }
}

//发货数量变化重新查询运费
const handleCalcFreightPrice = useDebounceFn(() => {
  if (Object.keys(addressRow.value).length) getShippingRates()
}, 500)

//接收勾选中的客户
const getExposeCustomerData = (val: any[]) => {
  if (!val || !val.length) return
  if (form.value.customer.user_id && form.value.customer.user_id !== val[0].id) {
    form.value.tableList = []
    form.value.deliveryAddress = {
      id: '',
      address: '',
      freight: ''
    }
    addressRow.value = {}
    // 新增：切换客户时重置到付状态
    freightCollect.value = false
  }
  form.value.customer.user_id = val[0].id
  form.value.customer.username = val[0].cusname
  form.value.customer.email = val[0].email
  form.value.customer.role = val[0].role
  partnerName.value = ''
  console.log(222, peopleList.value)
  console.log(333, val[0].partner)
  if (val[0].partner && val[0].partner.length) {
    form.value.partner = val[0].partner.join(',')
    peopleList.value.forEach((item: any) => {
      if (val[0].partner.includes(item.value)) {
        partnerName.value += item.label + ','
      }
    })
  }

  if (val[0].owner_id && val[0].owner) {
    form.value.owner = val[0].owner_id
    ownerName.value = val[0].owner
  }
}

//接收勾选中的商品
const getExposeMultipleData = (val: any[]) => {
  if (!val || !val.length) return
  form.value.tableList = val.flatMap((item: Record<string, any>) => [{ ...item, ship_quantity: 1 }])
}

//接收勾选中的收货地址
const getExposeAddressData = (val: any[]) => {
  if (!val || !val.length) return
  form.value.deliveryAddress.id = val[0].id
  form.value.deliveryAddress.address = val[0].address
  console.log(val[0])
  addressRow.value = val[0]
  getShippingRates()
}

//删除某一行
const handleDelete = (index: number) => {
  ElMessageBox.confirm(t('purchase.logistics.confirmDeletion'), t('purchase.logistics.tips'), {
    confirmButtonText: t('common.confirm'),
    cancelButtonText: t('common.cancel'),
    type: 'warning'
  })
    .then(() => {
      form.value.tableList.splice(index, 1)
      if (!form.value.tableList.length) {
        form.value.receiptMethod = 1
        form.value.deliveryAddress.freight = ''
        // 新增：清空商品时重置到付状态
        freightCollect.value = false
      }
    })
    .catch(() => {})
}

//获取枚举
const getDropDownBoxInfo = async () => {
  const resp = await getEnumApi({ field: 'all' })
  brandList.value = resp.data.brand
  warehouseList.value = resp.data.warehouse
  typeList.value = resp.data.is_futures
  receiptMethodList.value = resp.data.delivery_method
  agingList.value = resp.data.prescription
  howToFileYourTaxesList.value = resp.data.tax_package
}

//打开账单地址弹框
const handleSelectBillingAddress = () => {
  if (!form.value.customer.user_id)
    return ElMessage.warning(t('common.selectText') + ' ' + t('dealerAssetManagement.customer'))
  nextTick(() => {
    DialogSelectBillingAddressRef!.value!.dialogVisible = true
    DialogSelectBillingAddressRef!.value!.initialize(
      form.value.customer.user_id,
      form.value.billingAddress.id
        ? [
            {
              id: form.value.billingAddress.id,
              address: form.value.billingAddress.address
            }
          ]
        : []
    )
  })
}

//接收账单地址数据
const getExposeBillingAddressData = (val: any[]) => {
  console.log(val, 98)
  if (!val || !val.length) return
  form.value.billingAddress.id = val[0].id
  form.value.billingAddress.address = val[0].address
}

onMounted(async () => {
  console.log('Delivery.vue 挂载', route, route.query)
  if (route.query.customer_id && route.query.cusname && route.query.productIds) {
    await getpeopleList()
    getCustomerList()
    getProductList()
  }
  dynamicallySelectData()
  getDropDownBoxInfo()
})

//初始化请求
const peopleList = ref<any[]>([])
const getpeopleList = async () => {
  const params = JSON.parse(JSON.stringify(form.value))
  params.role = 'user'
  const resp = await getOrderEnumApi(params)
  peopleList.value = resp.data.operator
}

const dynamicallySelectData = () => {
  // 动态选择数据
  form.value.owner = userStore.getUserInfo?.id ?? 0
  ownerName.value = userStore.getUserInfo?.username ?? ''
}
const getCustomerList = async () => {
  const currentQuery = route.query
  const params = {
    cusname: currentQuery.cusname,
    role: 'distributor',
    pageIndex: 1,
    pageSize: 10
  }
  const resp = await getCustomerListApi(params)
  let arr = resp.data?.list?.filter((item: any) => item.id == currentQuery.customer_id)
  if (arr.length) {
    getExposeCustomerData(arr)
  }
}
const getProductList = async () => {
  const currentQuery = route.query
  const params = {
    user_id: currentQuery.customer_id,
    pageIndex: 1,
    pageSize: 500
  }
  const resp = await getListApi(params)
  let str = currentQuery?.productIds
  console.log('商品id', str, resp)
  let arr: any[] = []
  resp.data?.list.forEach((item: any) => {
    if (str?.includes(item.wid + '_' + item.product_id)) {
      arr.push(item)
    }
  })

  console.log('商品id', arr)
  form.value.tableList = arr.flatMap((item: Record<string, any>) => [{ ...item, ship_quantity: 1 }])
}
//打开选择负责人弹框
const DialogOwnerCheckedRef = ref()
const handleOpenOwner = () => {
  nextTick(() => {
    DialogOwnerCheckedRef.value!.dialogVisible = true
    DialogOwnerCheckedRef.value!.initialize(form.value.owner ? [{ id: form.value.owner }] : [])
  })
}
//接收勾选中的负责人
const ownerName = ref('')
const getExposeOwnerData = (val: any[]) => {
  console.log('负责人', val)
  if (!val || !val.length) return
  form.value.owner = val[0].id
  ownerName.value = val[0].cname
}
//接收勾选中的合伙人//打开选择合伙人弹框
const partnerName = ref('')
const handleOpenPartner = () => {
  nextTick(() => {
    DialogPartnerCheckedRef.value!.dialogVisible = true
    DialogPartnerCheckedRef.value!.initialize(
      form.value.partner
        ? form.value.partner.split(',').map((item) => ({ id: Number(item.trim()) }))
        : []
    )
  })
}
const getExposePartnerData = (val: any[]) => {
  if (!val || !val.length) return
  if (form.value.partner && form.value.partner !== val[0].id) {
  }
  form.value.partner = val.map((item: any) => item.id).join(',')
  partnerName.value = val.map((item: any) => item.cname).join(',')
}
</script>

<style lang="less" scoped></style>
